import time

graph = {}
# 开始节点
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2

# a节点
graph["a"] = {}
graph["a"]["fin"] = 1

# b节点到下一节点的距离
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5

# 结束节点没有邻居节点了
graph["fin"] = {}

infinity = float("inf")  # 无限大

# 创建开销表
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity


# 存储到子节点的父节点
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None

# 创造记录过的节点记录表
processed = []


def find_lowest_cost_node(costs):
    lowest_cost = float("inf")  # 无穷大
    lowest_cost_node = None  # 最低开销的节点
    for node in costs:  # 遍历所有节点 {"a":6,"b":2,"fin":inf}
        cost = costs[node]
        if cost < lowest_cost and node not in processed :  # 如果当前节点的开销更低且未处理过，就将其视为开销最低的节点
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node


node = find_lowest_cost_node(costs)  # 在未处理的节点中找出开销最小的节点


while node is not None:  # 这个while循环在所有节点都被处理过后结束
    cost = costs[node]
    neighbors = graph[node]
    for n in neighbors.keys():  # 遍历当前节点的所有邻居
        new_cost = cost + neighbors[n]
        if costs[n] > new_cost:  # 如果经当前节点前往该邻居节点更近，就更新邻居节点
            costs[n] = new_cost
            parents[n] = node  # 同时将该邻居的父节点设置为当前节点
    processed.append(node)  # 将当前节点标记为处理过
    node = find_lowest_cost_node(costs)  # 找出接下啦要处理的节点，并循环
print(parents)
print(cost)

